package homework;

import java.util.Random;
import java.util.Scanner;

public class Day2_homeWork3_migong {
    public static void main(String[] args) {
        int[][] maze = generateMaze(5, 5);
        int playerX = 0;
        int playerY = 0;
        maze[playerX][playerY] = 0; // 入口必须可通行
        maze[maze.length - 1][maze[0].length - 1] = 0; // 出口必须可通行
        Scanner scanner = new Scanner(System.in);

        while (true) {
            printMaze(maze, playerX, playerY);
            // 检查是否到出口
            if (playerX == maze.length - 1 && playerY == maze[0].length - 1) {
                System.out.println("恭喜你，成功走出迷宫！");
                break;
            }
            // 获取输入
            System.out.print("请输入移动方向（w:上, s:下, a:左, d:右）：");
            char direction = scanner.next().charAt(0);
            // 移动
            int newX = playerX;
            int newY = playerY;
            switch (direction) {
                case 'w': // 上
                    newX = playerX - 1;
                    break;
                case 's': // 下
                    newX = playerX + 1;
                    break;
                case 'a': // 左
                    newY = playerY - 1;
                    break;
                case 'd': // 右
                    newY = playerY + 1;
                    break;
                default:
                    System.out.println("输入无效，请重新输入！");
                    continue;
            }
            
            // 检查新位置是否合法且可通行
            if (newX >= 0 && newX < maze.length && newY >= 0 && newY < maze[0].length && maze[newX][newY] == 0) {
                playerX = newX;
                playerY = newY;
            } else {
                System.out.println("无法移动到此位置，请重新输入！");
            }
        }
        
        // 关闭 Scanner
        scanner.close();
    }

    // 生成随机迷宫的方法
    public static int[][] generateMaze(int rows, int cols) {
        Random random = new Random();
        int[][] maze = new int[rows][cols];
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // 随机生成 0 或 1，0 表示可通行，1 表示不可通行
                maze[i][j] = random.nextInt(2);
            }
        }
        
        return maze;
    }

    // 打印迷宫和玩家位置的方法
    public static void printMaze(int[][] maze, int playerX, int playerY) {
        for (int i = 0; i < maze.length; i++) {
            for (int j = 0; j < maze[i].length; j++) {
                if (i == playerX && j == playerY) {
                    System.out.print("★ "); // 玩家当前位置
                } else {
                    System.out.print(maze[i][j] + " ");
                }
            }
            System.out.println();
        }
    }
}
